package com.dnjn.happiness.emo.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.SysSiteVO;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.system.api.RemoteConfigService;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemoteSiteService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.emo.domain.EmoTeamNumberOfCommHistory;
import com.dnjn.happiness.emo.service.IEmoTeamNumberOfCommHistoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 团队历史沟通人数 留180天数据Controller
 *
 * @author happiness
 * @date 2023-10-28
 */
@Tag(name = "emoHistory团队历史沟通人数 留180天数据", description = "团队历史沟通人数 留180天数据")
@RestController
@RequestMapping("/emoTeamNumberOfCommHistory")
public class EmoTeamNumberOfCommHistoryController extends BaseController {
    @Autowired
    private IEmoTeamNumberOfCommHistoryService emoTeamNumberOfCommHistoryService;

    @Autowired
    private RemoteUserService userService;

    @Autowired
    private RemoteDeptService deptService;

    @Autowired
    private RemoteConfigService configService;

    @Autowired
    private RemoteSiteService siteService;

    private static final Logger log = LoggerFactory.getLogger(EmoTeamNumberOfCommHistoryController.class);

    /**
     * 查询团队历史沟通人数 留180天数据列表
     */
    @RequiresPermissions("emo:history:list")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody EmoTeamNumberOfCommHistory emoTeamNumberOfCommHistory, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page page = Page.of(current, size);
        Page<EmoTeamNumberOfCommHistory> list = emoTeamNumberOfCommHistoryService.page(page, Wrappers.query(emoTeamNumberOfCommHistory));
        return success(list);
    }

    /**
     * 导出团队历史沟通人数 留180天数据列表
     */
    @Log(title = "团队历史沟通人数 留180天数据", businessType = BusinessType.EXPORT)
    @RequiresPermissions("emo:history:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmoTeamNumberOfCommHistory emoTeamNumberOfCommHistory) {
        List<EmoTeamNumberOfCommHistory> list = emoTeamNumberOfCommHistoryService.list(Wrappers.query(emoTeamNumberOfCommHistory));
        ExcelUtil<EmoTeamNumberOfCommHistory> util = new ExcelUtil<EmoTeamNumberOfCommHistory>(EmoTeamNumberOfCommHistory.class);
        util.exportExcel(response, list, "团队历史沟通人数 留180天数据数据");
    }

    /**
     * 获取团队历史沟通人数 留180天数据详细信息
     */
    @RequiresPermissions("emo:history:query")
    @GetMapping(value = "/{id}")
    public AjaxResult get(@PathVariable("id") Long id) {
        return success(emoTeamNumberOfCommHistoryService.getById(id));
    }

    /**
     * 新增团队历史沟通人数 留180天数据
     */
    @Log(title = "团队历史沟通人数 留180天数据", businessType = BusinessType.INSERT)
    @RequiresPermissions("emo:history:add")
    @PostMapping
    public AjaxResult add(@RequestBody EmoTeamNumberOfCommHistory emoTeamNumberOfCommHistory) {
        emoTeamNumberOfCommHistory.setCreateBy(SecurityUtils.getUsername());
        return toAjax(emoTeamNumberOfCommHistoryService.save(emoTeamNumberOfCommHistory));
    }

    /**
     * 修改团队历史沟通人数 留180天数据
     */
    @Log(title = "团队历史沟通人数 留180天数据", businessType = BusinessType.UPDATE)
    @RequiresPermissions("emo:history:edit")
    @PutMapping
    public AjaxResult edit(@RequestBody EmoTeamNumberOfCommHistory emoTeamNumberOfCommHistory) {
        return toAjax(emoTeamNumberOfCommHistoryService.updateById(emoTeamNumberOfCommHistory));
    }

    /**
     * 删除团队历史沟通人数 留180天数据
     */
    @Log(title = "团队历史沟通人数 留180天数据", businessType = BusinessType.DELETE)
    @RequiresPermissions("emo:history:remove")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(emoTeamNumberOfCommHistoryService.removeBatchByIds(Arrays.asList(ids)));
    }


    /**
     * 报表查询当前部门下的需沟通人数历史
     */
    @Operation(summary = "报表查询当前部门下的需沟通人数历史")
    @PostMapping("/currenDeptHistoryCounts")
    public AjaxResult currenDeptHistoryCounts(@RequestParam("siteId") Long siteId,
                                              @RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String startTime, @RequestParam(required = false) @Parameter(description = "yyyy-MM-dd") String endTime) {
        //厂区id是否判空？
        Assert.notNull(siteId,"厂区id不能为空!");
        Long userId = SecurityUtils.getUserId();
        SysUser user = new SysUser();
        R<SysUser> result = userService.selectUserById(userId, SecurityConstants.INNER);
        if(StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
            user = result.getData();
        }
        Long currentDeptId = user.getDeptId();
        if (null == currentDeptId){
            log.warn("报表查询当前部门下的需沟通人数历史----->当前登录用户Id为空");
            return error("当前用户部门Id为空");
        }
        if (currentDeptId.equals(100L)){
            R<SysSiteVO> resultSite = siteService.getInfoById(siteId, SecurityConstants.INNER);
            if(StringUtils.isNotNull(resultSite) && StringUtils.isNotNull(resultSite.getData())){
                currentDeptId = resultSite.getData().getDeptId();
            }
        }
        //如果两个日期为空时，默认获取当前日期前两周的
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            LocalDate now = LocalDate.now();
            startTime = now.minusDays(14).toString();
            endTime = now.toString();
        }
        List<EmoTeamNumberOfCommHistory> list = emoTeamNumberOfCommHistoryService.currenDeptHistoryCounts(startTime, endTime, currentDeptId);

        return AjaxResult.success(list);
    }


    /**
     * 定时记录每个部门需沟通人数
     */
    @Operation(summary = "测试定时记录每个部门需沟通人数")
    @GetMapping("/testRecordingCommunicationCount")
    public void recordingCommunicationCount() {
        //临界值
        Integer num = 0;
        R<String> result = configService.getThresholdDateaApi(SecurityConstants.INNER);
        if(StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
            num = Integer.parseInt(result.getData());
        }

        List<Long> deptIdListAll = new ArrayList<>();
        R<List<Long>> resultListAll = deptService.getListAll(SecurityConstants.INNER);
        if(StringUtils.isNotNull(resultListAll) && StringUtils.isNotNull(resultListAll.getData())){
            deptIdListAll = resultListAll.getData();
        }
        for (Long deptId : deptIdListAll) {
            //所有子部门
            List<SysDept> deptChildList = new ArrayList<>();
            final R<List<SysDept>> deptListResult = deptService.getDeptListByDeptId(deptId,SecurityConstants.INNER);
            if(StringUtils.isNotNull(deptListResult) && StringUtils.isNotNull(deptListResult.getData())){
                deptChildList = deptListResult.getData();
            }
            //把当前部门也加进去
            //所有子部门ID集合
            List<Long> deptIdList = deptChildList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIdList.add(deptId);
            Long count = null;
            R<Long> resultCount = userService.getCommunicationCount(num,deptIdList,SecurityConstants.INNER);
            if(StringUtils.isNotNull(resultCount) && StringUtils.isNotNull(resultCount.getData())){
                count = resultCount.getData();
            }
            EmoTeamNumberOfCommHistory numberOfCommHistory = new EmoTeamNumberOfCommHistory()
                    .setCount(count)
                    .setCurrDate(LocalDate.now())
                    .setDeptId(deptId);
            //落库
            emoTeamNumberOfCommHistoryService.save(numberOfCommHistory);
        }
    }

}
